<template>
    <van-sticky>
        <van-nav-bar :title="title" left-text="返回" left-arrow @click-left="onClickLeft" />
    </van-sticky>
    <div v-if="loading">
        <CustomLoading :text="loadingText" />
    </div>
    <div v-else-if="hasRenWuDetail">
        <div class="step-title" v-if="checkStatus('进行中')">当前步骤（作业人员执行任务）</div>
        <div class="step-title" v-if="checkStatus('已完成')">当前步骤（牵头人审批任务）</div>
        <van-cell-group v-if="checkStatus('已完成') && isPlanLeader" class="approval-input-group">
            <van-field v-model="approvalOpinion" label="审批意见" type="textarea" placeholder="请输入审批意见" rows="3" />
        </van-cell-group>
        <div class="approval-buttons" v-if="checkStatus('已完成') && isPlanLeader">
            <van-button type="success" class="approval-button" @click="handleAgree">同意</van-button>
            <van-button type="danger" class="approval-button" @click="handleReject">拒绝</van-button>
        </div>
        <div v-if="checkStatus('进行中') && isTaskExecutor" class="task-execute-container">
            <van-cell-group class="task-cell-group">
                <van-cell title="任务执行" @click="executeRenWu()" class="task-cell" />
            </van-cell-group>
            <van-button class="cache-button" size="normal" :type="hasDataCache ? 'success' : 'default'"
                @click="handleCache">
                {{ hasDataCache ? '已缓存' : '未缓存' }}
            </van-button>
        </div>
        <div v-if="checkStatus('待下发')" class="step-title">当前步骤（综合员分配作业人员）</div>
        <div v-else class="step-title">历史步骤</div>
        <van-cell-group v-if="checkStatus(['已完成', '归档'])">
            <van-cell title="任务执行" is-link @click="executeRenWu()" />
        </van-cell-group>
        <div v-if="checkStatus(['待下发', '进行中']) && checkUser('综合员')">
            <van-cell-group>
                <van-field v-model="formData.date" label="日期" placeholder="点击选择日期" @click="isCalendarShow = true"
                    readonly />
            </van-cell-group>
            <van-calendar v-model:show="isCalendarShow" @confirm="fillDate" />
            <van-cell-group>
                <van-field v-model="formData.FuZeRen" label="负责人" placeholder="点击搜索人员" @click="showUserSelector('负责人')"
                    readonly />
            </van-cell-group>
            <UserSelector ref="userFuZeRenRef" @fillUser="fillFuZeRen" :noCheckbox="true"
                :exclude-user-ids="excludeUserIds"></UserSelector>
            <van-cell-group>
                <van-field v-model="formData.CanYuRenYuan" label="参与人员" placeholder="点击搜索人员"
                    @click="showUserSelector('参与人员')" readonly type="textarea" />
            </van-cell-group>
            <UserSelector ref="userCanYuRenYuanRef" @fillUsers="fillCanYuRenYuan" :noCheckbox="false"
                :exclude-user-ids="excludeUserIds"></UserSelector>
            <van-button v-if="checkStatus('待下发')" type="primary" class="submit-button"
                @click="createRenWu">提交</van-button>
            <van-button v-if="checkStatus('进行中')" type="danger" class="return-button"
                @click="handleReassign">重新分派</van-button>
        </div>
        <div v-if="checkStatus('待下发')" class="step-title">历史步骤</div>
        <van-cell-group inset>
            <van-row>
                <van-col span="16" class="title-col">编号 {{ RenWuDetail.no }}</van-col>
                <van-col span="8" class="status-col">
                    <van-tag :color="getStatusColor(RenWuDetail.status)" round class="status-tag">
                        {{ RenWuDetail.status }}
                    </van-tag>
                </van-col>
            </van-row>
            <div class="content-div">
                <span class="bold-span">专项名称：</span>
                <span class="data-span">{{ RenWuDetail.zxPlanName }}</span><br>
                <span class="bold-span">专项描述：</span>
                <span class="data-span">{{ RenWuDetail.zxPlanRemark }}</span><br></br>
                <span class="bold-span">变电所：</span>
                <span class="data-span">{{ RenWuDetail.locationName }}</span><br>
                <span v-if="checkStatus('进行中')">
                    <span class="bold-span">日期：</span>
                    <span class="data-span">{{ formatDate(RenWuDetail.date) }}</span><br>
                    <span class="bold-span">负责人：</span>
                    <span class="data-span">{{ RenWuDetail.leaderName }}</span><br>
                    <span class="bold-span">参与人员：</span>
                    <span class="data-span">{{ RenWuDetail.memberNames.replaceAll(",", "、") }}</span><br>
                </span>
            </div>
        </van-cell-group>
        <van-button type="danger" class="return-button" v-if="checkStatus('归档') && isPlanLeader"
            @click="handleApprovalReturn">退回</van-button>
    </div>
</template>
<script setup>
import { onMounted, ref, computed, onUnmounted } from 'vue';
import UserSelector from '@/components/UserSelector.vue';
import { getStatusColor, convertDict } from '@/utils/Misc.js';
import { showConfirmDialog, showFailToast, showSuccessToast } from 'vant';
import CustomLoading from '@/components/CustomLoading.vue';
import zxlzAPI from '@/api/zxlz';
import db from "@/utils/Dexie.js";
import { errorNotify, deepEqual } from "@/utils/Misc";
import { useRouter, useRoute } from 'vue-router'
const router = useRouter();
const route = useRoute();
import useStore from '@/store/index';
const store = useStore();
const title = ref("任务详情");
const RenWuDetail = ref({});
const hasRenWuDetail = ref(false);
const userFuZeRenRef = ref(null);
const userCanYuRenYuanRef = ref(null);
const isCalendarShow = ref(false);
const formData = ref({})
const submitData = ref({})
const approvalOpinion = ref('');
const excludeUserIds = ref([]);
const selectedMemberIds = ref([]);
const isPlanLeader = ref(false)
const hasDataCache = ref()
const loading = ref(false)
const loadingText = ref('数据加载中...')
const isTaskExecutor = computed(() => {
    const userId = store.user.id;
    const leaderId = RenWuDetail.value.leaderId;
    const memberIds = RenWuDetail.value.memberIds ? RenWuDetail.value.memberIds.split(',') : [];
    return userId === leaderId || memberIds.includes(userId);
});
const onClickLeft = () => {
    router.back();
};
onMounted(() => {
    window.scrollTo(0, 0);
    getRenWuDetail()
})

const saveToIndexedDB = async () => {
    const id = String(new URLSearchParams(window.location.search).get("id") || '');
    const cacheItem = await db.zxlzCache
        .where("id")
        .equals(id)
        .first()
    const pureData = cacheItem?.data;
    const pureRequirement = cacheItem?.requirement;
    const pureFiles = cacheItem?.files;
    const pureRenWuDetail = JSON.parse(JSON.stringify(RenWuDetail.value))
    try {
        await db.zxlzCache.put({ id: id, detail: pureRenWuDetail, data: pureData, requirement: pureRequirement, files: pureFiles });
    } catch (error) {
        errorNotify("RenWuDetail.vue", "saveToIndexedDB", error);
    }
};
const loadFromIndexedDB = async () => {
    const id = new URLSearchParams(window.location.search).get("id");
    const cacheData = await db.zxlzCache.get(id);
    if (cacheData != undefined) {
        RenWuDetail.value = cacheData.detail;
        hasRenWuDetail.value = true;
        if (cacheData.data != undefined) {
            hasDataCache.value = true;
        }
    } else {
        showFailToast({
            message: "没有缓存数据",
            forbidClick: false,
            duration: 0,
        });
    }
}
const handleCache = () => {
    const id = new URLSearchParams(window.location.search).get('id');
    if (hasDataCache.value) {
        showConfirmDialog({
            title: '清空缓存',
            message: '是否确认清空缓存内容？该操作无法撤销。',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            onConfirm: async () => {
                const cacheItems = await db.zxlzCache.where('id').equals(id).toArray();
                if (cacheItems.length > 0) {
                    const updatedItem = {
                        ...cacheItems[0],
                        data: undefined,
                        files: undefined,
                        requirement: undefined
                    };
                    await db.zxlzCache.put(updatedItem);
                    hasDataCache.value = false;
                }
            },
        }).catch(() => { });
    } else if (!hasDataCache.value) {
        executeRenWu()
    }
}
const checkStatus = (conditions) => {
    const currentStatus = RenWuDetail.value.status;
    if (Array.isArray(conditions)) {
        return conditions.includes(currentStatus);
    }
    return currentStatus === conditions;
}
const checkUser = (targetRoles) => {
    const userRoles = store.user.roleNames || '';
    if (Array.isArray(targetRoles)) {
        return targetRoles.some(role => userRoles.includes(role));
    }
    return userRoles.includes(targetRoles);
};
const showUserSelector = (type) => {
    if (type === '负责人') {
        if (formData.value.FuZeRenId != undefined) {
            formData.value.FuZeRen = '';
            excludeUserIds.value = excludeUserIds.value.filter(id => id !== formData.value.FuZeRenId)
        }
        userFuZeRenRef.value.showUserSelector();
    } else if (type === '参与人员') {
        if (formData.value.CanYuRenYuanIds != undefined) {
            excludeUserIds.value = excludeUserIds.value.filter(id => !formData.value.CanYuRenYuanIds.includes(id));
        }
        if (formData.value.CanYuRenYuanIds != undefined) {
            userCanYuRenYuanRef.value.setSelectedUserIds(formData.value.CanYuRenYuanIds);
        }
        userCanYuRenYuanRef.value.showUserSelector();
    }
};
const formatDate = (date) => {
    date = new Date(date);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
};
const formatDateTime = (date) => {
    date = new Date(date);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};
const fillDate = (value) => {
    isCalendarShow.value = false;
    formData.value.date = formatDate(value);
    submitData.value.date = formatDateTime(value);
}
const fillFuZeRen = (data) => {
    formData.value.FuZeRen = data.name;
    formData.value.FuZeRenId = data.id;
    submitData.value.leaderId = data.id;
    excludeUserIds.value = [...excludeUserIds.value, data.id];
}
const fillCanYuRenYuan = (data) => {
    const names = data.map(item => item.name);
    const ids = data.map(item => item.id);
    formData.value.CanYuRenYuan = names.join('、');
    formData.value.CanYuRenYuanIds = ids;
    submitData.value.memberIds = ids.join(",");
    excludeUserIds.value = [...excludeUserIds.value, ...ids];
}
const formatRenWuDetail = (zxPlan) => {
    const {
        id,
        createdAt,
        ...rest
    } = zxPlan;
    return {
        ...rest,
        id: id,
        no: "RW" + createdAt.split("-").join("").split(" ")[0] + "-" + id.split("-")[1],
        status: convertDict("专项任务状态", "v2l", zxPlan.status),
    };
};
const getRenWuDetail = () => {
    if (store.offlineMode) {
        // 从store中读取离线模式标志，为true时使用缓存数据
        loadFromIndexedDB();
    } else if (navigator.onLine) {
        // 在线模式下从网络获取数据
        loading.value = true;
        loadingText.value = '数据加载中...';
        const id = new URLSearchParams(window.location.search).get('id');
        zxlzAPI.getTaskById(id).then(async res => {
            loading.value = false;
            hasRenWuDetail.value = true;
            RenWuDetail.value = formatRenWuDetail(res.data.zxTask);
            isPlanLeader.value = store.user.id == res.data.zxTask.zxPlanLeaderId;
            saveToIndexedDB();
            const cacheItem = await db.zxlzCache
                .where("id")
                .equals(RenWuDetail.value.id)
                .first();
            hasDataCache.value = cacheItem && Array.isArray(cacheItem.data) && cacheItem.data.length > 0;
        }).catch((error) => {
            errorNotify("RenWuDetail.vue", "getRenWuDetail", error);
            loading.value = false;
        });
    } else {
        // 网络离线时使用缓存数据
        loadFromIndexedDB();
    }
}
const createRenWu = () => {
    loading.value = true;
    loadingText.value = '数据提交中...';
    submitData.value.id = RenWuDetail.value.id;
    if (submitData.value.date == undefined || submitData.value.leaderId == undefined || submitData.value.memberIds == undefined) {
        showFailToast('必填项不能\n为空');
        loading.value = false;
        return;
    }
    zxlzAPI.assignTask(submitData.value).then(res => {
        loading.value = false;
        showSuccessToast('下发成功！');
        router.back()
    }).catch((error) => {
        errorNotify("RenWuDetail.vue", "createRenWu", error);
        loading.value = false;
    })
};
const handleReassign = () => {
    loading.value = true;
    loadingText.value = '数据提交中...';
    submitData.value.id = RenWuDetail.value.id;
    if (submitData.value.date == undefined || submitData.value.leaderId == undefined || submitData.value.memberIds == undefined) {
        showFailToast('必填项不能\n为空');
        loading.value = false;
        return;
    }
    zxlzAPI.reassignTask(submitData.value).then(res => {
        loading.value = false;
        showSuccessToast('已重新分派！');
        router.back()
    }).catch((error) => {
        errorNotify("RenWuDetail.vue", "handleReassign", error);
        loading.value = false;
    })
};
const executeRenWu = () => {
    router.push({
        path: '/ZhuangXiang/RenWu/Execute',
        query: {
            id: RenWuDetail.value.id,
            status: RenWuDetail.value.status
        }
    })
}
const handleAgree = () => {
    const id = new URLSearchParams(window.location.search).get('id');
    if (approvalOpinion.value == "") {
        approvalOpinion.value = "同意";
    }
    loading.value = true;
    loadingText.value = '数据提交中...';
    const approvalForm = {
        id: id,
        isApproval: true,
        remark: approvalOpinion.value
    }
    zxlzAPI.leaderApproval(approvalForm).then(res => {
        loading.value = false;
        showSuccessToast('审批成功！');
        router.back()
    }).catch((error) => {
        errorNotify("RenWuDetail.vue", "handleAgree", error);
        loading.value = false;
    })
};
const handleReject = () => {
    const id = new URLSearchParams(window.location.search).get('id');
    if (approvalOpinion.value == "") {
        showFailToast('审批意见不能为空！');
        return
    }
    loading.value = true;
    loadingText.value = '数据提交中...';
    const approvalForm = {
        id: id,
        isApproval: false,
        remark: approvalOpinion.value
    }
    zxlzAPI.leaderApproval(approvalForm).then(res => {
        loading.value = false;
        showSuccessToast('审批成功！');
        router.back()
    }).catch((error) => {
        errorNotify("RenWuDetail.vue", "handleReject", error);
        loading.value = false;
    })
};
const handleApprovalReturn = () => {
    const id = new URLSearchParams(window.location.search).get("id");
    loading.value = true;
    loadingText.value = '数据提交中...';
    zxlzAPI.leaderApprovalReturn(id).then(res => {
        loading.value = false;
        showSuccessToast('退回成功！');
        router.back()
    }).catch((error) => {
        errorNotify("RenWuDetail.vue", "handleApprovalReturn", error);
        loading.value = false;
    })
};
</script>
<style scoped>
.approval-input-group {
    margin: 1rem 1rem 0.5rem;
}

.approval-buttons {
    display: flex;
    gap: 1rem;
    padding: 0 1rem;
    margin-bottom: 1rem;
    transition: all 0.3s ease;
}

.approval-button {
    flex: 1;
    height: 44px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.return-button {
    margin: 0 1rem;
    width: calc(100% - 2rem);
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.close-loop-btn {
    margin-right: 1rem;
}

.step-title {
    font-size: 16px;
    color: #333;
    margin: 1.2rem 0 0.8rem 1rem;
    padding-left: 0.75rem;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
}

.step-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 3px;
    background: linear-gradient(to bottom, #1989fa, #40a9ff);
    border-radius: 3px;
}

:deep(.van-cell-group) {
    border: 1px solid #eee;
    margin: 0.5rem 1rem;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    background-color: #ffffff;
}

:deep(.van-cell-group:active) {
    transform: translateY(1px);
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
}

.title-col {
    font-weight: 600;
    padding-left: 1rem;
    padding-top: 1rem;
    margin-bottom: 0.5rem;
    color: #333;
}

.status-col {
    padding-top: 1rem;
    padding-right: 1.2rem;
    text-align: right;
}

.status-tag {
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 12px;
    font-weight: 500;
}

.content-div {
    padding-left: 1rem;
    padding-right: 1rem;
    padding-bottom: 1rem;
    line-height: 1.6;
}

.bold-span {
    font-weight: 600;
    display: inline-block;
    color: #555;
    margin-bottom: 0.5rem;
}

.data-span {
    color: #333;
    margin-bottom: 0.5rem;
    display: inline-block;
}

.description-span {
    color: #333;
    margin: 0;
    text-align: justify;
    line-height: 1.6;
    display: inline-block;
    margin-bottom: 0.5rem;
}

.submit-button {
    margin: 0 1rem;
    width: calc(100% - 2rem);
    height: 44px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.task-execute-container {
    display: flex;
    align-items: center;
    margin: 0.5rem 1rem;
    gap: 0.5rem;
}

.task-cell-group {
    flex: 4;
    margin: 0;
    border-radius: 12px;
    overflow: hidden;
}

.cache-button {
    flex: 1;
    font-size: 14px;
    padding: 0;
    border-radius: 8px;
    transition: all 0.3s ease;
}
</style>